package com.zx._10_设计模式.创建型模式.单例模式;

public class 练习题 {

    static enum Singleton6 {
        singleton;

        private Singleton6() {
        }

        public static Singleton6 getInstance() {
            return singleton;
        }
    }

    // 教学案例, 懒汉, 线程不安全
    static class Singleton1 {

        private static Singleton1 singleton;

        private Singleton1() {
        }

        public static Singleton1 getInstance() {
            if (singleton == null) {
                singleton = new Singleton1();
            }
            return singleton;
        }
    }

    // 饿汉, 线程安全
    static class Singleton2 {

        private static Singleton2 singleton = new Singleton2();

        private Singleton2() {
        }

        public static Singleton2 getInstance() {
            return singleton;
        }
    }

    // 懒汉线程安全方式1
    static class Singleton3 {

        private static Singleton3 singleton;

        private Singleton3() {
        }

        // 锁方法
        public synchronized static Singleton3 getInstance() {
            if (singleton == null) {
                singleton = new Singleton3();
            }
            return singleton;
        }

        // 锁这个类
        public static Singleton3 getInstance2() {
            synchronized (Singleton3.class) {
                if (singleton == null) {
                    singleton = new Singleton3();
                }
            }
            return singleton;
        }
    }

    // 懒汉线程安全方式2, 双重校验
    static class Singleton4 {

        private static Singleton4 singleton;

        private Singleton4() {
        }

        public static Singleton4 getInstance() {
            if (singleton == null) {
                synchronized (singleton) {
                    if (singleton == null) {
                        singleton = new Singleton4();
                    }
                }
            }
            return singleton;
        }
    }

    // 静态内部类，数据安全的
    static class Singleton5 {

        private Singleton5() {
        }

        public static Singleton5 getInstance() {
            return Singleton5Hanlder.singleton;
        }

        static class Singleton5Hanlder {

            static Singleton5 singleton = new Singleton5();
        }
    }


}
